﻿using System;
using System.Data;
using System.Web;
using System.Collections;
using System.Web.Services;
using System.Web.Services.Protocols;
using System.ComponentModel;
using Geoconcepts.Types;
using Geoconcepts.Common;
using Geoconcepts.SocialServices;
using Geoconcepts.TextMiningServices;


namespace Geoconcepts.Acquisition
{
    /// <summary>
    /// Descripción breve de GeoconceptsAcquisition
    /// </summary>
    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [ToolboxItem(false)]
    public class GeoconceptsAcquisition : System.Web.Services.WebService
    {

        /// <summary>
        /// Converts a KML file to an OWL file.
        /// </summary>
        /// <param name="strFullURL">Full URI or path of the file</param>
        /// <param name="strWebOrFile">"web" or "file"</param>
        /// <returns></returns>
        [WebMethod(Description = "Generates an OWL version of a KML file. The results are given in OWL format complying with Geoconcepts ontology: http://www.geospatialmeaning.eu/geo-ontologies-survey/GeoConcepts/GeoConcepts_v1.2_20080326Lite_swrl.owl The file can be loaded from web or from local file.")]
        public string ConvertKml2Owl(string strFullURL, string strWebOrFile)
        {
            #region Variables
            string strResult = "";
            //GeoconceptsDataSet dtsGeoconceptTest = new GeoconceptsDataSet();
            GeoconceptsDataSet dtsGeoconcept = new GeoconceptsDataSet();
            byte[] fileOWL = null;
            #endregion Variables

            try
            {
                Kml2Owl oKml2Owl = new Kml2Owl();
                SemanticConversion oSemanticConversion = new SemanticConversion();

                //#region Fichero de Test si no se provee ningún fichero con datos
                //if (strFullURL == null || strFullURL == "")
                //{
                //    strFullURL = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().CodeBase) + "\\Test\\GeoconceptsTest.xml";
                //    strWebOrFile = "file";
                //}
                //#endregion Fichero de Test si no se provee ningún fichero con datos
                //dtsGeoconceptTest.ReadXml(strFullURL);

                dtsGeoconcept = oKml2Owl.ConvertKmlToGeoconceptsDataset(strFullURL);

                fileOWL = oSemanticConversion.ConvertGeoconceptsToOWL(dtsGeoconcept);

                strResult = Ficheros.ConvertirBytesAFicheroTemporal(fileOWL, "owl");

                return strResult;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        /// <summary>
        /// Converts a KML file to an OWL file.
        /// </summary>
        /// <param name="strFullURL">Full URI or path of the file</param>
        /// <param name="strWebOrFile">"web" or "file"</param>
        /// <returns></returns>
        [WebMethod(Description = "Generates an OWL version of a GisFile file. The results are given in OWL format complying with Geoconcepts ontology: http://www.geospatialmeaning.eu/geo-ontologies-survey/GeoConcepts/GeoConcepts_v1.2_20080326Lite_swrl.owl The file can be loaded from web or from local file.")]
        public string ConvertGisFile2Owl(string strFullURL, string strWebOrFile)
        {
            #region Variables
            string strResult = "";
            //GeoconceptsDataSet dtsGeoconceptTest = new GeoconceptsDataSet();
            GeoconceptsDataSet dtsGeoconcept = new GeoconceptsDataSet();
            byte[] fileOWL = null;
            #endregion Variables

            try
            {
                Kml2Owl oKml2Owl = new Kml2Owl();
                SemanticConversion oSemanticConversion = new SemanticConversion();

                //#region Fichero de Test si no se provee ningún fichero con datos
                //if (strFullURL == null || strFullURL == "")
                //{
                //    strFullURL = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().CodeBase) + "\\Test\\GeoconceptsTest.xml";
                //    strWebOrFile = "file";
                //}
                //#endregion Fichero de Test si no se provee ningún fichero con datos
                //dtsGeoconceptTest.ReadXml(strFullURL);

                dtsGeoconcept = oKml2Owl.ConverGisFileToGeoconceptsDataset(strFullURL);
                
                fileOWL = oSemanticConversion.ConvertGeoconceptsToOWL(dtsGeoconcept);

                strResult = Ficheros.ConvertirBytesAFicheroTemporal(fileOWL, "owl");

                return strResult;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        /// <summary>
        /// Entry point to KB generation. Shows Acquisition steps.
        /// </summary>
        /// <param name="strCity">City Name</param>
        /// <param name="bGetDataFromWeb">If false, get data from stored files (fastest option)</param>
        /// <returns></returns>
        [WebMethod(Description = "Generates an OWL version of a GisFile file. The results are given in OWL format complying with Geoconcepts ontology: http://www.geospatialmeaning.eu/geo-ontologies-survey/GeoConcepts/GeoConcepts_v1.2_20080326Lite_swrl.owl It is recommended to use bGetDataFromWeb to false.")]
        public string GenerateKnowledgeBase(string strCity,bool bGetDataFromWeb)
        {
            #region Variables
            string strResult = "";
            GeoResource dtsGeoResource = new GeoResource();
            string strAlternateNames = "";
            string strXmlTempFile = "";
            TermExtractionStats dtsTermExtractionStats = new TermExtractionStats();
            #endregion 

            try
            {
                #region Step 1. Initialize parameters
                GeoSource dtsGeoSource = new GeoSource("");
                BoundingBox dtsBoundingBox = new BoundingBox("");


                BoundingBox.RectanglesRow[] drRectangles = (BoundingBox.RectanglesRow[])dtsBoundingBox.Rectangles.Select("Description like '%" + strCity + "%'");

                if (drRectangles == null || drRectangles.Length == 0)
                {
                    Exception exc = new Exception("Bounding box not founded for this city");
                    throw exc;
                }
                foreach (GeoSource.GeoSourcesRow drGeoSource in dtsGeoSource.GeoSources)
                {
                    drGeoSource.minLat = drRectangles[0].MinLat;
                    drGeoSource.maxLat = drRectangles[0].MaxLat;
                    drGeoSource.minLon = drRectangles[0].MinLong;
                    drGeoSource.maxLon = drRectangles[0].MaxLong;
                }
                #endregion Step 1. Initialize parameters


                #region Step 2. Adquire referenced data from the web or from file.
                GeoReferencedData svcGeoReferencedData = new GeoReferencedData();

                

                if (bGetDataFromWeb)
                {
                    // Get references from Panoramio and Flickr by default.
                    dtsGeoResource = svcGeoReferencedData.GetGeoResources(dtsGeoSource);
                }
                else
                { 
                    string strXmlFile = AppDomain.CurrentDomain.BaseDirectory + @"\XmlFiles";
                    strXmlFile = strXmlFile + "\\panoramio_" + strCity + ".xml";

                    dtsGeoResource.ReadXml(strXmlFile);
                }
                
                
                #endregion Step 2. Adquire referenced data from the web or from file.

                #region Step 2. Retrieve geoconcepts candidates.
                #region Get City Alternate Names, mostly in other languages
                Geonames svcGeonames = new Geonames();
                strAlternateNames = svcGeonames.GeonamesGetAllAdministrativeAlternateNames(strCity, drRectangles[0].CountryCode);
                #endregion Get City Alternate Names, mostly in other languages

                #region Build Text File
                strXmlTempFile = Ficheros.ObtenerFicheroTemporal("xml");

                #endregion Build Text File

                #region Text mining and get geoconcepts list.
                YahooTermExtractor svcYahooTermExtractor = new YahooTermExtractor();
                svcYahooTermExtractor.GetGeoConceptsCandidates(strXmlTempFile, strCity, strAlternateNames);
                #endregion Text mining and get geoconcepts list.

                #endregion Step 2. Retrieve geoconcepts candidates.

                // Step 3. Generate spatial objects and spatial relationships


                // Step 4. Create OWL file from spatial objects


                return strResult;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        
    }
}
